package com.ehotting.mqbd.core.manager;

import com.ehotting.eaf.redis.service.RedisService;
import com.ehotting.mqbd.api.MQDBConstants;
import com.ehotting.mqbd.api.bean.solver.ModuleInfoBean;
import com.ehotting.mqbd.api.enums.ProtocolTypeEnum;
import com.ehotting.mqbd.core.config.MqbdCoreServerInfoConfig;
import com.ehotting.mqbd.core.mq.consumer.MessageConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class ModuleManager {

    private static Logger log = LoggerFactory.getLogger(ModuleManager.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private MqbdCoreServerInfoConfig mqbdCorePropertyConfig;

    public void loadModule(){

        log.info("Start loadModule.");

        List<ModuleInfoBean> sysModuleInfoList = mqbdCorePropertyConfig.getModules();
        log.info("sysModuleInfoList.size():{}",sysModuleInfoList.size());

        for(ModuleInfoBean sysModuleInfo : sysModuleInfoList){
            redisService.setCacheObject(
                    MQDBConstants.MODULE_INFO_KEY +sysModuleInfo.getModule()
                    ,sysModuleInfo);
        }

        log.info("Finish loadModule.");
    }

    public List<ModuleInfoBean> getModuleInfoList(){
        List<ModuleInfoBean> moduleInfoList = new ArrayList<>();
        Collection<String> keys = redisService.keys(MQDBConstants.MODULE_INFO_KEY + "*");

        for(String key :keys){
            //log.info("key:{}",key);
            ModuleInfoBean sysModuleInfo = redisService.getCacheObject(key);
            moduleInfoList.add(sysModuleInfo);
        }

        return moduleInfoList;
    }

    public ProtocolTypeEnum getServerProtocolTypeByModule(String module){
        ModuleInfoBean sysModuleInfo = getByModule(module);
        if(sysModuleInfo !=  null){
            return sysModuleInfo.getProtocol();
        }
        return ProtocolTypeEnum.HTTP;
    }

    public ModuleInfoBean getByModule(String module){
        ModuleInfoBean sysModuleInfo = redisService.getCacheObject(MQDBConstants.MODULE_INFO_KEY +module);
        return sysModuleInfo;
    }

    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    public void setMqbdCorePropertyConfig(MqbdCoreServerInfoConfig mqbdCorePropertyConfig) {
        this.mqbdCorePropertyConfig = mqbdCorePropertyConfig;
    }
}
